﻿using System;
using System.Reactive.Linq;

namespace TrafficWatcher.Models
{
    public class DirectionDurationService : IDirectionDurationService
    {
        private bool enabled;
        private readonly Settings settings;
        private IDisposable directionProviderSubscriber;
        
        public DirectionDurationService(Settings settings)
        {
            Duration = TimeSpan.Zero;

            this.settings = settings;

            this.settings.SettingsChanged += (_, __) =>
                {
                    if (Enabled)
                    {
                        Stop();
                        Start();
                    }
                };
        }

        public bool Enabled
        {
            get
            {
                return enabled;
            }
            set
            {
                if (enabled == value) return;

                if (!enabled)
                    Start();
                else
                    Stop();
            }
        }

        public TimeSpan Duration { get; private set; }
        public event EventHandler DurationChanged;

        public void Start()
        {
            if (enabled) return;
            enabled = true;

            var observer = Observable
                .Interval(TimeSpan.FromSeconds(60)).StartWith(-1)
                .Select(_ => settings.CurrentDirectionsProvider.CalculateDuration(settings.Start, settings.Finish));

            directionProviderSubscriber = observer.ObserveOnDispatcher().Subscribe(SetDuration);
        }

        public void Stop()
        {
            if (!enabled) return;
            directionProviderSubscriber.Dispose();
            enabled = false;
            SetDuration(TimeSpan.Zero);
        }
        
        private void SetDuration(TimeSpan ts)
        {
            Duration = ts;
            var handler = DurationChanged;
            if (handler != null) handler(this, EventArgs.Empty);
        }
    }
}
